<template>
  <el-dialog width="500px" v-bind="$attrs" @close="handleClose" @open="handleOpen">
    <el-form
      @submit.prevent.native
      label-position="top"
      :model="form"
      ref="form"
      :rules="type === 'APPLE' ? appleRules : huaweiRules"
    >
      <el-form-item :label="$t('contact_us.type')" prop="type">
        <el-select
          v-model="type"
          :placeholder="$t('contact_us.type')"
          style="width: 100%"
        >
          <el-option
            v-for="item in typeList"
            :key="item.code"
            :value="item.code"
            :label="item.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="name">
        <template #label class="startRequire"
          ><span>{{$t('modules.pass.passtypeid')}}</span>
          <el-tooltip placement="top" :content="$t('flypass.pass_type_id_upload')">
            <svg-icon class="ml-2"icon-class="OutlinedQuestionCircle" />
          </el-tooltip>
        </template>
        <el-input
          maxlength="32"
          show-word-limit
          v-model="form.name"
          @blur="() => (form.name = form.name.trim())"
          placeholder="PassTypeIdentifier"
        ></el-input>
      </el-form-item>
      <el-form-item prop="certificate" v-show="type === 'APPLE'">
        <template #label class="startRequire"
          ><span>{{$t('modules.pass.certificate_file')}}</span>
          <el-tooltip placement="top" :content="$t('flypass.p12_certificate')">
            <svg-icon class="ml-2"icon-class="OutlinedQuestionCircle" />
          </el-tooltip>
        </template>
        <el-upload
          ref="uploadFile"
          class="w-full"
          drag
          action
          :before-upload="fileCheck"
          :multiple="false"
          :limit="1"
          :http-request="fileUpload"
          :show-file-list="false"
          :auto-upload="true"
          :on-change="fileChange"
          :file-list="fileList"
          accept=".p12"
        >
          <div v-if="progressPercent === 0">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              {{ $t('developer.upload_drag_tip') }}<em> {{ $t('developer.click_upload') }}</em>
            </div>
            <div class="el-upload__tip" slot="tip">{{ $t('modules.pass.p12_tip') }}</div>
          </div>
          <el-progress
            type="circle"
            :percentage="progressPercent"
            :status="
              progressPercent === 100 ? 'success' : progressPercent === -100 ? 'exception' : ''
            "
            v-else
          ></el-progress>
        </el-upload>
      </el-form-item>
      <el-form-item prop="key" v-show="type === 'APPLE'">
        <template #label class="startRequire"
          ><span>{{$t('modules.pass.key')}}</span>
          <el-tooltip placement="top" :content="$t('flypass.p12_key')">
            <svg-icon class="ml-2"icon-class="OutlinedQuestionCircle" />
          </el-tooltip>
        </template>
        <el-input
          show-password
          maxlength="512"
          show-word-limit
          v-model="form.key"
          @blur="() => (form.key = form.key.trim())"
          :placeholder="$t('modules.pass.key')"
        ></el-input>
      </el-form-item>
      <el-form-item :label="$t('common.description') + ':'" prop="description">
        <el-input
          type="textarea"
          maxlength="256"
          show-word-limit
          v-model="form.description"
          @blur="() => (form.description = form.description.trim())"
          :placeholder="$t('common.description')"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button text @click="handleClose()">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" :loading="confirmLoading" @click="confirm()">{{
          $t('common.confirm')
        }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script>
import { fileUpload, addPassTypeIdentifier } from '@/api/pass-generate'
import axios from 'axios'
import JSEncrypt from 'jsencrypt'
export default {
  data() {
    return {
      confirmLoading: false,
      type: 'APPLE',
      form: {
        type: 'APPLE',
        name: '',
        key: '',
        description: ''
      },
      typeList: [
        {
          code: 'APPLE',
          label: 'Apple'
        }
        // ,
        // {
        //   code: 'HUAWEI',
        //   label: 'Huawei'
        // }
      ],
      fileList: [],
      dataForm: [],
      progressPercent: 0,
      source: '',
      fileUuid: ''
    }
  },
  computed: {
    appleRules() {
      return {
        type: [
          {
            required: true,
            trigger: 'blur',
            message: this.$t('page.tip_select')
          }
        ],
        name: [
          {
            required: true,
            trigger: 'blur',
            message: this.$t('page.tip_enter')
          }
        ],
        certificate: [
          {
            required: true,
            trigger: 'blur',
            message: this.$t('page.tip_enter')
          }
        ],
        key: [
          {
            required: true,
            trigger: 'blur',
            message: this.$t('page.tip_enter')
          }
        ]
      }
    },
    huaweiRules() {
      return {
        type: [
          {
            required: true,
            trigger: 'blur',
            message: this.$t('page.tip_select')
          }
        ],
        name: [
          {
            required: true,
            trigger: 'blur',
            message: this.$t('page.tip_enter')
          }
        ]
      }
    }
  },
  methods: {
    encrytKey(key) {
      let encryptor = new JSEncrypt()
      let publicKey =
        'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4zjkRL0KFb0WoPU39rVxHOps/BbruZWhYatfkcrqd7wieOGCMnJoZ800JvoelAcdqthnfrBBXXdtFCJX2J/CF0tVsCnFsVRh+Vbq2zAWnvqQRYO2V2+vRWs04WwP0d59vZw6K8hQrOJH5hggZotMgvHf8YCVo+TnwUvTVc2iguhl9UlUQs2FtOtaG5uN3efPjICakHIF51/jZw06tLY7e4njA5HIMgOqZ3PMOllZkC37IeQ1V113e6Ec+Tf5JuyWpDRoPlMdoQ+Yo36pkTY+jeu/NbxBdM72aawVJ3WFDz+E8vTptCpjDrRaz41uI+1zN68d7nZfemhN8QvYeJFj1QIDAQAB'
      encryptor.setPublicKey(publicKey)
      return encryptor.encrypt(key)
    },
    confirm() {
      this.$confirm(this.$t('modules.pass.add_file_tip'), this.$t('modules.pass.warning'), {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'info'
      })
        .then(() => {
          let data
          this.$refs['form'].validate((valid) => {
            if (valid) {
              this.confirmLoading = true
              if (this.type === 'APPLE') {
                data = {
                  passTypeIdentifier: this.form.name,
                  p12Id: this.fileUuid,
                  pwd: this.encrytKey(this.form.key),
                  channel: this.type,
                  description: this.form.description
                }
              } else {
                data = {
                  passTypeIdentifier: this.form.name,
                  channel: this.type,
                  description: this.form.description
                }
              }
              addPassTypeIdentifier(data)
                .then((res) => {
                  this.confirmLoading = false
                  this.$emit('update:model-value', false)
                  this.$emit('refresh')
                  this.$message({
                    type: 'success',
                    message: this.$t('page.add_success')
                  })
                })
                .catch((err) => {
                  this.$confirmError(err)
                  this.confirmLoading = false
                })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: this.$t('modules.pass.add_canceled')
          })
        })
    },
    handleOpen() {
      this.$refs['form'].resetFields()
      this.type = 'APPLE'
    },
    handleClose() {
      this.$refs['form'].resetFields()
      if (this.type === 'APPLE') {
        this.cancelUpload()
      } else {
      }
      this.$emit('update:model-value', false)
    },
    fileChange(file, fileList) {
      this.fileList = fileList
    },
    // 上传前的判断
    fileCheck(file) {
      let fileName = file.name
      //   this.uploadStatus = 1
      let fileType = fileName.slice(fileName.lastIndexOf('.') + 1).toLowerCase()
      if (fileType !== 'p12') {
        this.$message.error(this.$t('modules.pass.p12_tip'))
        // this.uploadStatus = 0
        return false
      }
      return true
    },
    reset() {
      console.log('this.form.type', this.type)
      if (this.type === 'APPLE') {
        //   this.uploadStatus = 0
        this.fileList = []
        //   this.dataForm.remark = ''
        //   this.showProgressPercent = false
        this.progressPercent = 0
        this.$refs['uploadFile'].clearFiles()
      }
    },
    //取消上传
    cancelUpload() {
      //   this.uploadStatus = 0
      // this.source.cancel('canceled')
      this.reset()
      this.$refs.uploadFile.abort()
    },
    // 上传文件
    fileUpload(data) {
      this.progressPercent = 0
      //   this.showUploadErrorInfo = false
      const formdata = new FormData()
      formdata.append('file', data.file)
      //   this.uploadStatus = 1
      const config = {
        onUploadProgress: (progressEvent) => {
          // progressEvent.loaded:已上传文件大小
          // progressEvent.total:被上传文件的总大小
          // this.showProgressPercent = true
          this.progressPercent = Number(
            ((progressEvent.loaded / progressEvent.total) * 99).toFixed(2)
          )
        }
      }
      const CancelToken = this.$axios.CancelToken
      this.source = CancelToken.source()
      fileUpload(formdata, config, this.source)
        .then((res) => {
          this.fileUuid = res.fileUuid
          this.progressPercent = 100
          this.form.certificate = true
          //返回数据
          // this.dataForm.fileToken = res.fileToken
          // this.dataForm.uploadTime = res.uploadTime
          // this.dataForm.fileSize = res.fileSize
          // this.dataForm.fileMd5 = res.fileMd5
          // this.dataForm.fileName = res.fileName
          // this.dataForm.fileType = res.fileType
          // if (this.dataForm.fileContent.length === 0) {
          //   //上传文件夹为空
          //   this.$message.error(this.$t('modules.pass.file_empty'))
          //   this.cancelUpload()
          // } else {
          //   this.$message({
          //     message: this.$t('modules.pass.upload_successfully'),
          //     type: 'success'
          //   })
          // }
          // this.uploadStatus = 3 //上传成功
          // this.progressPercent = 100
          // }
        })
        .catch((err) => {
          // 上传失败
          this.progressPercent = -100
          this.$confirmError(err)
          this.form.certificate = ''
          // this.uploadStatus = 2
          // if (this.uploadStatus !== 0) {
          //   if (e.message) {
          //     this.showUploadErrorInfo = true
          //     let message = e.message
          //     if (message.indexOf('timeout') >= 0) {
          //       message = this.$t('common.connect_server_timeout')
          //     }
          //     this.dataForm.uploadErrorInfo = message
          //   } else {
          //     this.showUploadErrorInfo = true
          //     this.dataForm.uploadErrorInfo = e.message
          //   }
          // }
        })
    }
  }
}
</script>

<style scoped>
.startRequire ::before {
  content: '*';
  color: var(--el-color-danger);
  margin-right: 4px;
}
</style>
